﻿ #include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QStandardPaths>
#include <QDir>
#include <QDebug>
#include <QKeyEvent>
#include "common/Utils.h"
#include <QLabel>
#include <QScreen>
#include <FunctionForm.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow),m_isConnectionState(false),bFristReadRunState(false),
      bFristReadFaultState(false),bFristReadCurFalState(false),bFristReadVolFalState(false),
    bFristReadTempFalState(false),m_RxUDPCnt(0)
{

    /********************1.初始化UI界面*******************/
    ui->setupUi(this);

    /********************2.初始化检查配置文件*******************/
    // 获取“我的文档”路径
    QString documentsPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);

    // 创建名为“20KWData”的文件夹
    QString folderName = "FilamentPowerSupply";
    QString folderPath = QDir(documentsPath).filePath(folderName);
    QDir dir(folderPath);

    if (!dir.exists()) {
        if (dir.mkdir(".")) {
            qDebug() << "文件夹创建成功：" << folderPath;
        } else {
            qDebug() << "文件夹创建失败";
        }
    } else {
        qDebug() << "文件夹已存在：" << folderPath;
    }

    // 获取并输出文件夹路径
    qDebug() << "文件夹路径：" << folderPath;
    //    QString iniFilePath = QCoreApplication::applicationDirPath() + "/Settings.ini";
    QString iniFilePath = folderPath + "/Settings.ini";
    QString configFilePath = folderPath + "/017Config.ini";

    m_MainSettings = new QSettings(iniFilePath,QSettings::IniFormat);
    m_ConifgSettings = new QSettings(configFilePath,QSettings::IniFormat);

    m_Style = m_MainSettings->value("SystemSet/Style","black").toString();




    //*****************创建默认参数*****************

    // pcCaliDialog = new CaliDialog(this);


    // 创建QFile对象
    QFile file(configFilePath);
    // 检查文件是否存在
    if (!file.exists())
    {
        // 文件不存在，尝试创建文件
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            m_ConifgSettings->setValue("Config/Station1","1,2,3,4,5,6,7,8");
            m_ConifgSettings->setValue("Config/Station2","9,10,11,12,13,14,15,16");
            m_ConifgSettings->setValue("Config/ParentDialog","Notepad++");
            m_ConifgSettings->setValue("Config/NoWindow",0);
            m_ConifgSettings->setValue("Config/Width",1024);
            m_ConifgSettings->setValue("Config/Height",800);
            file.close();
        }
    }

    //工位的配置
    QString tempStr = m_ConifgSettings->value("Config/Station1","1,2,3,4,5,6,7,15").toString().remove(' '); // 移除所有空格;
    QStringList strList = tempStr.split(",");
    foreach (QString str, strList) {
        m_ListStation1 << str.toUInt();
    }
    tempStr = m_ConifgSettings->value("Config/Station2","8,9,10,11,12,13,14,16").toString().remove(' '); // 移除所有空格;
    strList.clear();
    strList = tempStr.split(",");
    foreach (QString str, strList) {
        m_ListStation2 << str.toUInt();
    }

    //统一调整字体大小
    m_FontSize = m_MainSettings->value("SystemSet/FontSize",13).toInt();

    m_defaultIp = m_MainSettings->value("Link/Ip","192.168.0.170").toString();
    m_defaultPort = m_MainSettings->value("Link/Port",502).toUInt();

    increaseFontSize(this,m_FontSize-13);

    ui->tabWidget->setCurrentIndex(0);

    ui->statusbar->showMessage("子界面初始化",2000);


    foreach (quint8 value, m_ListStation1) {
        FunctionForm* pcFunctionForm = new FunctionForm(nullptr);
        pcFunctionForm->setSettings(value,m_MainSettings);
        ui->tabWidget->addTab(pcFunctionForm,QString("电源%1").arg(value));
    }


    foreach (quint8 value, m_ListStation2) {
        FunctionForm* pcFunctionForm = new FunctionForm(nullptr);
        pcFunctionForm->setSettings(value,m_MainSettings);
        ui->tabWidget->addTab(pcFunctionForm,QString("电源%1").arg(value));
    }



    // ui->tab_1->setSettings(1,m_MainSettings);
    // ui->tab_2->setSettings(2,m_MainSettings);
    // ui->tab_3->setSettings(3,m_MainSettings);
    // ui->tab_4->setSettings(4,m_MainSettings);
    // ui->tab_5->setSettings(5,m_MainSettings);

    // ui->tab_6->setSettings(6,m_MainSettings);
    // ui->tab_7->setSettings(7,m_MainSettings);
    // ui->tab_8->setSettings(8,m_MainSettings);
    // ui->tab_9->setSettings(9,m_MainSettings);
    // ui->tab_10->setSettings(10,m_MainSettings);

    // ui->tab_11->setSettings(11,m_MainSettings);
    // ui->tab_12->setSettings(12,m_MainSettings);
    // ui->tab_13->setSettings(13,m_MainSettings);
    // ui->tab_14->setSettings(14,m_MainSettings);
    // ui->tab_15->setSettings(15,m_MainSettings);

    // ui->tab_16->setSettings(16,m_MainSettings);



    /********************3.记录16个子界面的指针*******************/
    QList<FunctionForm*> temp_FunctionForms = this->findChildren<FunctionForm*>();
    //根据界面名称排序
    for(int i = 0 ; i < 16 ; i ++)
    {
        for(int j = 0 ; j < temp_FunctionForms.size() ; j++)
        {
            if(temp_FunctionForms[j]->getIndex() == i+1)
            {
                m_FunctionForms << temp_FunctionForms[j];
                break;
            }
        }
    }

    if(m_ConifgSettings->value("Config/NoWindow",0).toInt() == 1)
    {
        setWindowFlags(Qt::FramelessWindowHint); // 设置无边框
        //showMinimized();
    }

    loadStyle(m_Style);

    this->setWindowTitle("017灯丝电源");
    ui->statusbar->showMessage("软件启动完成",2000);
    resize(m_ConifgSettings->value("Config/Width",1024).toInt(),
           m_ConifgSettings->value("Config/Height",800).toInt());


    QTimer::singleShot(1000,this,[&]()
    {
    /********************4.建立通信类*******************/
    m_Thread = new QThread();
    m_ModBusTcpWorker = new ModBusTcpWorker(nullptr);

    // 将 worker 移动到新线程，并确保在线程结束时删除
    m_ModBusTcpWorker->moveToThread(m_Thread);
    connect(m_Thread, &QThread::finished, m_Thread, &QObject::deleteLater);

    // 当 worker 被删除时，结束线程
    connect(m_ModBusTcpWorker, &QObject::destroyed, m_Thread, &QThread::quit);

    // 获取QCoreApplication的实例
    QCoreApplication *app = QCoreApplication::instance();
    if(app)
    {
        // 确保在应用程序退出时线程已经结束
        connect(app, &QCoreApplication::aboutToQuit, m_Thread, &QThread::quit);
        connect(m_Thread, &QThread::finished, app, &QCoreApplication::quit);
    }

    connect(this,&MainWindow::sig_SetProNameDevType,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetProNameDevType,Qt::QueuedConnection);
    connect(this,&MainWindow::sig_SetIPPort,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetIPPort,Qt::QueuedConnection);
    connect(this,&MainWindow::sig_SetReadStartAddressAndRegisterCount,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetReadStartAddressAndRegisterCount,Qt::QueuedConnection);
    //connect(this,&MainWindow::sig_SetWriteStartAddressAndRegisterCount,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetWriteStartAddressAndRegisterCount,Qt::QueuedConnection);
    connect(this,&MainWindow::sig_StartLoopReadRegister,m_ModBusTcpWorker,&ModBusTcpWorker::slotStartConnection,Qt::QueuedConnection);

    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_readBoolData,this,&MainWindow::slot_readBoolData,Qt::QueuedConnection);
    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_readfloatData,this,&MainWindow::slot_readfloatData,Qt::QueuedConnection);
    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_readIntData,this,&MainWindow::slot_readIntData,Qt::QueuedConnection);
    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_ConnectionState,this,&MainWindow::slot_ConnectionState,Qt::QueuedConnection);
    //connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_ReadState,this,&MainWindow::slot_ReadState,Qt::QueuedConnection);
    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_WriteDataQueueFinish,this,&MainWindow::slot_WriteDataQueueFinish,Qt::QueuedConnection);

    //屏幕分辨率
    QScreen *screen = QGuiApplication::primaryScreen();
    QSize ScreenSize = screen->size();



    //子界面FunctionFormz 直接发送数据的槽函数连接
    for (FunctionForm* functionForm : qAsConst( m_FunctionForms))
    {
        //队列写消息
        connect(functionForm,&FunctionForm::sig_AddWriteQueue,m_ModBusTcpWorker,&ModBusTcpWorker::slotAddWriteQueue,Qt::QueuedConnection);
        //单次直接写消息
        //connect(functionForm,&FunctionForm::sig_SetWriteStartAddressAndRegisterCount,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetWriteStartAddressAndRegisterCount,Qt::QueuedConnection);
        //子界面的运行状态改变的发送按钮的槽函数
        connect(functionForm,&FunctionForm::sig_SetRunState,this,&MainWindow::slot_SetRunState);

        connect(functionForm,&FunctionForm::sig_Reset,this,&MainWindow::slot_Reset);

        connect(functionForm,&FunctionForm::sig_showMessage,this,&MainWindow::slot_showMessage);

        connect(functionForm,&FunctionForm::sig_openIPSet,this,&MainWindow::slot_openIPSetDialog);

        connect(functionForm,&FunctionForm::sig_ReSetIniFlie,this,&MainWindow::slot_ReSetIniFile);

        functionForm->setScreenSize(ScreenSize);//全屏分辨率，弹子界面居中使用
    }

    if(m_FunctionForms.size() > 0)
    {
        connect(m_FunctionForms[0],&FunctionForm::sig_GeneralReset,this,&MainWindow::slot_GeneralReset);//总复位
    }

    connect(this,&MainWindow::sig_AddWriteQueue,m_ModBusTcpWorker,&ModBusTcpWorker::slotAddWriteQueue,Qt::QueuedConnection);
//    connect(this,&MainWindow::sig_HandleWriteQueue,m_ModBusTcpWorker,&ModBusTcpWorker::slotHandleWriteQueue,Qt::QueuedConnection);


    //线程开始
    m_Thread->start();
    ui->statusbar->showMessage("初始化连接下位机",2000);

    //设置设备名称和类型ID 这个类被多次实例化区分使用，本次使用不上
    emit sig_SetProNameDevType("017",1);
    emit sig_SetIPPort(m_defaultIp,m_defaultPort);

    QList<int> ReadStartAddressList; //开始地址的列表
    QList<int> ReadRegisterCountList;//开始地址的个数

    // 运行状态开关 、 （总故障 电流故障 电压故障 温度故障） 、 电流 、 电压  设置起始地址和寄存器个数
    ReadStartAddressList  << 0 << 6 << 3100 << 3132  << 3600 ;
    ReadRegisterCountList << 1 << 7 << 32   << 32    << 64   ;

    emit sig_SetReadStartAddressAndRegisterCount(ReadStartAddressList,ReadRegisterCountList,3);

    emit sig_StartLoopReadRegister(true);//放下面的定时器中

    /********************6.恢复ini类的的*******************/

    //m_Timer = new QTimer(this); 子线程中有循环检测是否连接的函数
    //connect(m_Timer,&QTimer::timeout,this,&MainWindow::timeoutWatchDog);
    //m_Timer->start(1000);
    //timeoutWatchDog();

    /********************7.底部状态栏**********************/
    // 创建QLabel
//    QLabel *statusLabel = new QLabel(ui->statusbar);
//    statusLabel->setMaximumSize(20,20);
//    statusLabel->setScaledContents(true);

//    // 设置QLabel的图标
//    QPixmap pixmap(":/res/image/Offline.png"); // 替换为你的图标路径
//    statusLabel->setPixmap(pixmap);

//    // 将QLabel添加到状态栏
//    ui->statusbar->addPermanentWidget(statusLabel,1); // 使用addPermanentWidget使标签始终显示


    pcIPSetDialog = new IPSetDialog(this);
    pcIPSetDialog->setDefaultIpPort(m_defaultIp,m_defaultPort);
    connect(pcIPSetDialog,&IPSetDialog::sendIpAndPort,this,&MainWindow::slot_setIpAndPort);

    //qDebug() << "replaceFontSize:" << replaceFontSize("font-size: 10px;",17);

    //指定跟随一起关闭的父界面
    QString targetProcessName = m_ConifgSettings->value("Config/ParentDialog","Notepad++").toString();; // 替换为目标进程名
    monitor = new ProcessMonitor(targetProcessName,nullptr);


    //关闭程序联动一个程序
    monitor_Thread = new QThread();
    // 将 worker 移动到新线程，并确保在线程结束时删除
    monitor->moveToThread(monitor_Thread);
    connect(monitor_Thread, &QThread::finished, monitor_Thread, &QObject::deleteLater);

    // 当 worker 被删除时，结束线程
    connect(monitor, &QObject::destroyed, monitor_Thread, &QThread::quit);

    // 获取QCoreApplication的实例
    if(app)
    {
        // 确保在应用程序退出时线程已经结束
        connect(app, &QCoreApplication::aboutToQuit, monitor_Thread, &QThread::quit);
        connect(monitor_Thread, &QThread::finished, app, &QCoreApplication::quit);
    }
    connect(monitor, &ProcessMonitor::processClosed, this, &MainWindow::slot_processClosed,Qt::QueuedConnection);
    monitor_Thread->start();

    m_ParentLinkDialog = new ParentLinkDialog(this);
    m_ParentLinkDialog->hide();


    m_UDPThread = new QThread();
    m_UDPWorker = new UDPWorker(nullptr);
    m_UDPWorker->moveToThread(m_UDPThread);
    // 获取QCoreApplication的实例
    if(app)
    {
        // 确保在应用程序退出时线程已经结束
        connect(app, &QCoreApplication::aboutToQuit, m_UDPThread, &QThread::quit);
        connect(m_UDPThread, &QThread::finished, app, &QCoreApplication::quit);
    }
    connect(m_UDPWorker, &UDPWorker::sig_closeExe, this, &MainWindow::slot_processClosed,Qt::QueuedConnection);
    connect(m_UDPWorker, &UDPWorker::sig_handleData, this, &MainWindow::slot_RxUDPData,Qt::QueuedConnection);
    connect(m_UDPWorker, &UDPWorker::sig_DialogShowTxData, m_ParentLinkDialog, &ParentLinkDialog::setRxUDPData,Qt::QueuedConnection);
    connect(m_UDPWorker, &UDPWorker::sig_setReSize,this,&MainWindow::slot_ReSize,Qt::QueuedConnection);


    connect(this,&MainWindow::sig_TxUDPData,m_UDPWorker,&UDPWorker::slot_sendData,Qt::QueuedConnection);

    m_UDPRXTimer = new QTimer(this);

    m_UDPThread->start();
    connect(m_UDPRXTimer,&QTimer::timeout,this,&MainWindow::slot_RxUDPDataWatchDog);

    m_UDPRXTimer->start(2000);

    m_RxUDPDataPre << false << false << false << false;




    m_PowerRunFinishTimer = new QTimer(this);
    m_PowerRunFinishTimer->setSingleShot(true);//设置单次定时器
    connect(m_PowerRunFinishTimer,&QTimer::timeout,this,&MainWindow::slot_PowerRunFinishWatchDog);

    for(int i = 0 ; i < 16;i++)
        m_PowerRunFinishPre << false;

    });

    //设置大电源
    m_FunctionForms[m_ListStation1.last()-1]->setBigPower();
    m_FunctionForms[m_ListStation2.last()-1]->setBigPower();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slot_readBoolData(int MegId, QList<bool> data)
{
    switch (MegId) //消息的ID
    {
    case 1://运行开关的状态
    {
        if(data.size() != 16)
        {
            qDebug() << "返回的运行状态数量不等于16";
            return;
        }
        if(!bFristReadRunState)//第一次的初始化
        {
            bFristReadRunState = true;

            for(int i = 0 ; i < data.size() ; i++)
            {
//                foreach (auto functionForm ,m_FunctionForms)
//                {
//                    if(functionForm->objectName() == QString("tab_%1").arg(i+1) )
//                    {
//                        functionForm->setRunState(data.at(i));
//                        break;
//                    }
//                }
                m_FunctionForms[i]->setRunState(data.at(i));
            }
            m_ListRunStatePre = data;
        }
        else
        {
            for(int i = 0 ; i < data.size() ; i++)
            {
                if(m_ListRunStatePre.at(i) != data.at(i))//不等于则改状态
                {
                    m_FunctionForms[i]->setRunState(data.at(i));
                }
            }
            m_ListRunStatePre = data;
        }
    }
        break;
    case 2://总故障的状态
    {
        if(data.size() != 16)
        {
            qDebug() << "返回的故障状态数量不等于16";
            return;
        }
        if(!bFristReadFaultState)//第一次的初始化
        {
            bFristReadFaultState = true;

            for(int i = 0 ; i < data.size() ; i++)
            {
                m_FunctionForms[i]->setFaultState(data.at(i));
            }
            m_ListFaultStatePre = data;
        }
        else
        {
            for(int i = 0 ; i < data.size() ; i++)
            {
                if(m_ListFaultStatePre.at(i) != data.at(i))//不等于则改状态
                {
                     m_FunctionForms[i]->setFaultState(data.at(i));
                }
            }
            m_ListFaultStatePre = data;
        }
    }
        break;
    case 3://电流故障的状态
    {
        if(data.size() != 16)
        {
            qDebug() << "返回的电流故障状态数量不等于16";
            return;
        }
        if(!bFristReadCurFalState)//第一次的初始化
        {
            bFristReadCurFalState = true;

            for(int i = 0 ; i < data.size() ; i++)
            {
                m_FunctionForms[i]->setCurFaultState(data.at(i));
            }
            m_ListCurFalStatePre = data;
        }
        else
        {
            for(int i = 0 ; i < data.size() ; i++)
            {
                if(m_ListCurFalStatePre.at(i) != data.at(i))//不等于则改状态
                {
                     m_FunctionForms[i]->setCurFaultState(data.at(i));
                }
            }
            m_ListCurFalStatePre = data;
        }
    }
        break;

    case 4://电压故障的状态
    {
        if(data.size() != 16)
        {
            qDebug() << "返回的电流故障状态数量不等于16";
            return;
        }
        if(!bFristReadVolFalState)//第一次的初始化
        {
            bFristReadVolFalState = true;

            for(int i = 0 ; i < data.size() ; i++)
            {
                m_FunctionForms[i]->setVolFaultState(data.at(i));
            }
            m_ListVolFalStatePre = data;
        }
        else
        {
            for(int i = 0 ; i < data.size() ; i++)
            {
                if(m_ListVolFalStatePre.at(i) != data.at(i))//不等于则改状态
                {
                     m_FunctionForms[i]->setVolFaultState(data.at(i));
                }
            }
            m_ListVolFalStatePre = data;
        }
    }
        break;
    case 5://温度故障的状态
    {
        /****温度故障4个位表示改成了16个位表示*****/
        //if(data.size() != 4)
        if(data.size() != 16)
        {
            qDebug() << "返回的电流故障状态数量不等于16";
            return;
        }
        if(!bFristReadTempFalState)//第一次的初始化
        {
            bFristReadTempFalState = true;

            /*
            for(int i = 0 ; i< 7;i++)
            {
                m_FunctionForms[i]->setTempFaultState(data.at(0));
            }

            for(int i = 7 ; i< 14;i++)
            {
                m_FunctionForms[i]->setTempFaultState(data.at(1));
            }
            m_FunctionForms[14]->setTempFaultState(data.at(2));
            m_FunctionForms[15]->setTempFaultState(data.at(3));
            */
            for(int i = 0; i < 16 ; i++)
                m_FunctionForms[i]->setTempFaultState(data.at(i));

            m_ListTempFalStatePre = data;
        }
        else
        {
            /* ****温度故障4个位表示改成了16个位表示*****
            for(int i = 0 ; i< 7;i++)
            {
                m_FunctionForms[i]->setTempFaultState(data.at(0));
            }

            for(int i = 7 ; i< 14;i++)
            {
                m_FunctionForms[i]->setTempFaultState(data.at(1));
            }
            m_FunctionForms[14]->setTempFaultState(data.at(2));
            m_FunctionForms[15]->setTempFaultState(data.at(3));
            */
            for(int i = 0; i < 16 ; i++)
                m_FunctionForms[i]->setTempFaultState(data.at(i));

            m_ListTempFalStatePre = data;
        }
    }
        break;

    case 6://复位
    {
        if(data.size() != 16)
        {
            qDebug() << "返回的复位数量不等于4";
            return;
        }

        m_ListTempReSetPre = data;

    }
        break;

    // case 7://16个关闭电源
    // {
        // if(data.size() != 16)
        // {
        //     qDebug() << "关闭电源数量不等于16";
        //     return;
        // }

        // m_PowerClosePre = data;

    // }
    // break;

    case 8://运行完毕
    {
        if(data.size() != 16)
        {
            qDebug() << "运行完毕数量不等于16";
            return;
        }

        if(m_PowerRunFinishPre == data)
            return;

        QList<bool>  PowerFinish;
        PowerFinish << true << true;


        for(int i = 0 ; i < m_ListStation1.size() ; i++)
        {
            if(!data.at(m_ListStation1.at(i)-1))
            {
                PowerFinish[0] = false;
                break;
            }
        }

        for(int i = 0 ; i < m_ListStation2.size() ; i++)
        {
            if(!data.at(m_ListStation2.at(i)-1))
            {
                PowerFinish[1] = false;
                break;
            }
        }

        if(PowerFinish[0] || PowerFinish[1])
        {
            if(m_PowerRunFinishTimer->isActive())
                m_PowerRunFinishTimer->stop();
        }

        ui->btnPowerFinish_1->setChecked(PowerFinish.at(0));
        ui->btnPowerFinish_2->setChecked(PowerFinish.at(1));

        emit sig_TxUDPData(PowerFinish);

        QTimer::singleShot(50,this,[=](){
            emit sig_TxUDPData(PowerFinish);
        });

        if(PowerFinish.at(0) || PowerFinish.at(1))
            m_PowerRunFinishTimer->start(30000);//30秒后关闭置0

        m_PowerRunFinishPre = data;

    }
    break;

    default:
        break;
    }
}

void MainWindow::slot_readfloatData(int MegId, QList<float> data)
{
    switch (MegId) //消息的ID
    {
    case 3://电流
    {
        if(data.size() != 16)
        {
            qDebug() << "返回的电流数量不等于16";
            return;
        }

        for(int i = 0 ; i < data.size() ; i++)
        {
            m_FunctionForms[i]->setEleCurrentValue(data.at(i));
        }
    }
        break;
    case 4://电压
    {
        if(data.size() != 16)
        {
            qDebug() << "返回的电压数量不等于16";
            return;
        }
        for(int i = 0 ; i < data.size() ; i++)
        {
            m_FunctionForms[i]->setEleVolValue(data.at(i));
        }
    }
        break;
    default:
        break;
    }
}

void MainWindow::slot_readIntData(int MegId, QList<int> data)
{
    switch (MegId) //消息的ID
    {
    case 5://剩余次数
    {
        if(data.size() != 32)
        {
            qDebug() << "返回的剩余次数数量不等于32";
            return;
        }
        for(int i = 0 ; i < 16 ; i++)
        {
            m_FunctionForms[i]->setReMainValue(data.at(i),data.at(i+16));
        }
    }
    break;
    default:
        break;
    }
}

//读写的运行状态的发送
void MainWindow::slot_SetRunState(bool isRun,int index,bool Disconnect)
{
    QList<bool> RunState = m_ListRunStatePre;
    if(RunState.size() != 16)
        return;
    if(index < 1 || index > 16)
        return;

    RunState[index-1] = isRun;
    if(Disconnect)//运行中拔网线引发的状态改变
    {
        m_ListRunStatePre = RunState;
    }
    else
    {
        QList<quint16>  sendData;
        sendData <<  boolListToQuint16(RunState);

        //LX 20250523改队列写法
        WriteData* writeData1 = new WriteData(0,sendData.size(),sendData);
        emit sig_AddWriteQueue(writeData1);

        QTimer::singleShot(40,this,[=]()
        {
            emit sig_AddWriteQueue(writeData1);
        });
    }

}

void MainWindow::slot_Reset(int index)
{
    QList<bool> StateList = m_ListTempReSetPre;
    if(StateList.size() != 16)
        return;
    if(index < 1 || index > 16)
        return;

    StateList[index-1] = true;

    QList<quint16>  sendData;
    sendData <<  boolListToQuint16(StateList);

    WriteData* writeData1 = new WriteData(10,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData1);

    QTimer::singleShot(40,[=]()
    {
        emit sig_AddWriteQueue(writeData1);
    });
}

//总复位槽函数
void MainWindow::slot_GeneralReset()
{
    QList<quint16>  sendData;
    sendData <<  static_cast<quint16>(0xFFFF);//全置1

    WriteData* writeData1 = new WriteData(10,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData1);

    QTimer::singleShot(40,[=]()
    {
        emit sig_AddWriteQueue(writeData1);
    });
}

void MainWindow::slot_ConnectionState(bool isConnectionState)
{
    /*
    for (FunctionForm* functionForm : m_FunctionForms)
    {
        functionForm->setConnectionState(isConnectionState);
    }
    */

    m_isConnectionState = isConnectionState;//连接状态


    //连接成功后一次性下发消息给下位机
    if(isConnectionState)
    {
        ui->statusbar->showMessage("下位机已连接，开始同步数据",2500);
        SendDataAfterConnection();//
        for (FunctionForm* functionForm : m_FunctionForms)
        {
            functionForm->setConnectionState(true);
        }
    }
    else
    {
        for (FunctionForm* functionForm : m_FunctionForms)
        {
            functionForm->setConnectionState(false);
        }
        for(int i = 0 ; i < m_ListRunStatePre.size(); i++)
        {
            m_ListRunStatePre[i] = false;
        }
    }
}

//读状态正常才算连接
/*
void MainWindow::slot_ReadState(bool isState)
{
//    if(isState)
//    {
//        for (FunctionForm* functionForm : m_FunctionForms)
//        {
//            functionForm->setConnectionState(true);
//        }
//    }

    //isReadState = isState;
}
*/

void MainWindow::slot_WriteDataQueueFinish()
{
    ui->statusbar->showMessage("下发数据完成",2500);
}

void MainWindow::slot_showMessage(QString Msg)
{
    ui->statusbar->showMessage(Msg,2500);
}

void MainWindow::slot_openIPSetDialog(bool isOpen)
{
    if(isOpen)
        pcIPSetDialog->show();
    else
        pcIPSetDialog->close();
}

void MainWindow::slot_setIpAndPort(QString Ip, quint16 port)
{
    emit sig_StartLoopReadRegister(false);
    m_defaultIp = Ip;
    m_defaultPort = port;
    m_MainSettings->setValue("Link/Ip",m_defaultIp);
    m_MainSettings->setValue("Link/Port",m_defaultPort);
    emit sig_SetIPPort(Ip,port);
    emit sig_StartLoopReadRegister(true);
}

void MainWindow::slot_ReSize(int width, int height)
{
    //m_ConifgSettings->setValue("Config/Width",width);
    //m_ConifgSettings->setValue("Config/Height",height);
    resize(width,height);
}

//加载数据的界面QSettings
void MainWindow::slot_ReSetIniFile(QSettings *settings)
{
    if(settings)
    {
        copySettings(settings,m_MainSettings);
        foreach (auto function, m_FunctionForms)
        {
            function->ReSetTings(m_MainSettings);
        }
    }
}

void MainWindow::slot_processClosed()
{
    QCoreApplication::quit();
}

void MainWindow::slot_RxUDPData(QList<bool> bList)
{
    if(bList.size() != 4)
        return;

    m_RxUDPCnt = 3;//6秒不通信则停
    m_ParentLinkDialog->setHeartbeat(true);


    if(m_RxUDPDataPre == bList)
        return;

    ui->btnVaFinish_1->setChecked(bList.at(0));
    ui->btnVaFinish_2->setChecked(bList.at(1));
    ui->btnVaAlarm_1->setChecked(bList.at(2));
    ui->btnVaAlarm_2->setChecked(bList.at(3));

    QList<bool>  VaFinishList;
    for(int i = 0 ; i < 16; i++)
        VaFinishList << false;

    if(bList.at(0))//工位1真空完成
    {
        foreach (int index, m_ListStation1) {
            if(index<=16 && index >= 1)
            {
                VaFinishList[index-1] = true;
            }
            else
            {
                continue;
            }
        }
    }
    else
    {
        foreach (int index, m_ListStation1) {
            if(index<=16 && index >= 1)
            {
                VaFinishList[index-1] = false;
            }
            else
            {
                continue;
            }
        }
    }

    if(bList.at(1))//工位2真空完成
    {
        foreach (int index, m_ListStation2) {
            if(index<=16 && index >= 1)
            {
                VaFinishList[index-1] = true;
            }
            else
            {
                continue;
            }
        }
    }
    else
    {
        foreach (int index, m_ListStation2) {
            if(index<=16 && index >= 1)
            {
                VaFinishList[index-1] = false;
            }
            else
            {
                continue;
            }
        }
    }

    if(bList.at(2))//工位2报警
    {
        foreach (int index, m_ListStation1) {
            if(index<=16 && index >= 1)
            {
                VaFinishList[index-1] = false;
            }
            else
            {
                continue;
            }
        }
    }

    if(bList.at(3))//工位3报警
    {
        foreach (int index, m_ListStation2) {
            if(index<=16 && index >= 1)
            {
                VaFinishList[index-1] = false;
            }
            else
            {
                continue;
            }
        }
    }

    for(int i = 0 ; i < m_FunctionForms.size(); i++)
    {
        m_FunctionForms.at(i)->setRunState(VaFinishList[i]);
    }
    QList<quint16>  sendData;
    sendData <<  boolListToQuint16(VaFinishList);

    //LX 20250523改队列写法
    WriteData* writeData1 = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData1);

    QTimer::singleShot(40,this,[=]()
                       {
                           emit sig_AddWriteQueue(writeData1);
                       });

    m_RxUDPDataPre = bList;


}

void MainWindow::slot_RxUDPDataWatchDog()
{
    if(m_RxUDPCnt != 0)
        --m_RxUDPCnt;

    if(m_RxUDPCnt == 0)
    {
        m_RxUDPDataPre.clear();
        m_RxUDPDataPre << false << false << false << false;
        ui->btnVaFinish_1->setChecked(false);
        ui->btnVaFinish_2->setChecked(false);
        ui->btnVaAlarm_1->setChecked(false);
        ui->btnVaAlarm_2->setChecked(false);
        m_ParentLinkDialog->setHeartbeat(false);
    }
}

//延时完成置0
void MainWindow::slot_PowerRunFinishWatchDog()
{
    QList<bool> bList = {false,false};
    emit sig_TxUDPData(bList);
    ui->btnPowerFinish_1->setChecked(false);
    ui->btnPowerFinish_2->setChecked(false);

    QTimer::singleShot(1000,this,[=]()
                       {
                           emit sig_TxUDPData(bList);
                       });
}


//主函数的定时器函数
/*
void MainWindow::timeoutWatchDog()//
{


    if(!m_isConnectionState)//如果不在连接中，则请求连接
    {
        emit sig_StartLoopReadRegister(true);
    }
    else
    {
        m_Timer->stop();
    }
}
*/

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_P && event->modifiers() == Qt::ControlModifier) {
        qDebug() << "Ctrl+P 按键被捕获！";
        //打开IP配置界面
        if(pcIPSetDialog->isHidden())
            pcIPSetDialog->show();
        else
            pcIPSetDialog->close();
    }

    if (event->key() == Qt::Key_O && event->modifiers() == Qt::ControlModifier) {
        qDebug() << "Ctrl+P 按键被捕获！";
        //打开IP配置界面
        if(m_ParentLinkDialog->isHidden())
            m_ParentLinkDialog->show();
        else
            m_ParentLinkDialog->close();
    }
    /*
    else if (event->key() == Qt::Key_I && event->modifiers() == Qt::ControlModifier) {
        qDebug() << "Ctrl+P 按键被捕获！";
        //打开IP配置界面
        if(m_ConifgSettings->value("Config/NoWindow",1).toInt() == 1)
        {
            this->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::WindowCloseButtonHint); // 设置有边框
            m_ConifgSettings->setValue("Config/NoWindow",0);
        }
        else
        {
            this->setWindowFlags(Qt::FramelessWindowHint); // 设置无边框
            m_ConifgSettings->setValue("Config/NoWindow",1);
        }
    }
    */
    else if (event->key() == Qt::Key_Equal  && event->modifiers() == Qt::ControlModifier) {
        qDebug() << "Ctrl+ =  按键被捕获！";
        // 在这里执行你想要的操作

        if(m_Style == "white")
        {
            m_Style = "black";
            loadStyle(m_Style);
        }
        else if(m_Style == "black")
        {
            m_Style = "Multiple";
            loadStyle(m_Style);
        }
        else if(m_Style == "Multiple")
        {
            m_Style = "white";
            loadStyle(m_Style);
        }
        m_MainSettings->setValue("SystemSet/Style",m_Style);
    }
    else if (event->key() == Qt::Key_Minus  && event->modifiers() == Qt::ControlModifier) {
        qDebug() << "Ctrl+ -  按键被捕获！";
        if(m_Style == "white")
        {
            m_Style = "Multiple";
            loadStyle(m_Style);
        }
        else if(m_Style == "black")
        {
            m_Style = "white";
            loadStyle(m_Style);
        }
        else if(m_Style == "Multiple")
        {
            m_Style = "black";
            loadStyle(m_Style);
        }
        m_MainSettings->setValue("SystemSet/Style",m_Style);
    }
    else
    {
        // 对于其他按键，调用基类的 keyPressEvent 方法
        QMainWindow::keyPressEvent(event);
    }
}

/*
void MainWindow::resizeEvent(QResizeEvent *event)
{
    QMainWindow::resizeEvent(event);

       // 获取当前窗口的大小
       QSize size = event->size();

       // 打印当前窗口的大小
       qDebug() << "Current window size:" << size;
}
*/

//连接后发送消息
void MainWindow::SendDataAfterConnection()
{

    QList<quint16>  sendData1;//1.发送模式1电流
    QList<quint16>  sendData2;//2.发送模式1时间
    QList<quint16>  sendData3;//3.发送模式2起始电流
    QList<quint16>  sendData4;//4.发送模式2开通时间
    QList<quint16>  sendData5;//5.发送模式2关闭时间
    QList<quint16>  sendData6;//6.发送模式2循环次数
    QList<quint16>  sendData7;//7.发送模式3电流
    QList<quint16>  sendData8;//8.发送模式3时间
    QList<quint16>  sendData9;//9.发送模式3开通时间
    QList<quint16>  sendData10;//10.发送模式3关闭时间

    QList<quint16>  sendData11;//11.发送模式3循环次数
    QList<quint16>  sendData12;//12.发送模式3开通电压 即起始电流
    QList<quint16>  sendData13;//13.当前段数发送
    QList<quint16>  sendData14;//14.当前模式发送
    QList<quint16>  sendData15;//15.电流超值发送
    QList<quint16>  sendData16;//16.电压超值发送
    //遍历循环凑寄存器的 地址 下发下位机
    for(int i = 0 ; i < m_FunctionForms.size(); i++)
    {
        sendData1.clear();
        sendData2.clear();
        sendData7.clear();
        sendData8.clear();
        /*********************模式1*************************/
        m_MainSettings->beginGroup(QString("Power%1_Mode1").arg(i+1));
        for(int j = 1 ; j <= 20 ; j++)
        {
            //1.存模式1电流
            float fValue = m_MainSettings->value(QString("paragraph%1_EleCurrent").arg(j),0.0).toFloat();
            sendData1.append(floatToQuint16(fValue));

            //2.发送模式1时间
            quint32 iValue = static_cast<quint32>(m_MainSettings->value(QString("paragraph%1_Time").arg(j),0).toLongLong());
            sendData2.append( quint32toQuint16List(iValue));
        }
        m_MainSettings->endGroup();

        //1.发送模式1电流
        WriteData* writeData1 = new WriteData(100 + (i*40),sendData1.size(),sendData1);
        emit sig_AddWriteQueue(writeData1);

        //2.发送模式1时间
        WriteData* writeData2 = new WriteData(750 + (i*40),sendData2.size(),sendData2);
        emit sig_AddWriteQueue(writeData2);

        sendData7 = sendData1;
        sendData8 = sendData2;
        WriteData* writeData7 = new WriteData(2150  + (i*40) ,sendData7.size(),sendData7);
        emit sig_AddWriteQueue(writeData7);
        //8.发送模式3时间
        WriteData* writeData8 = new WriteData(1500  + (i*40) ,sendData8.size(),sendData8);
        emit sig_AddWriteQueue(writeData8);

        /*********************模式2*************************/

        m_MainSettings->beginGroup(QString("Power%1_Mode2").arg(i+1));
        //3.发送模式2起始电流
        float fValue1 = m_MainSettings->value("StartEleCurrent",0.0).toFloat();
        sendData3.append(floatToQuint16(fValue1));

        //4.发送模式2开通时间
        quint32 iValue1 = static_cast<quint32>(m_MainSettings->value("StartTime",0).toLongLong());
        sendData4.append( quint32toQuint16List(iValue1));

        //5.发送模式2关闭时间
        quint32 iValue2 = static_cast<quint32>(m_MainSettings->value("EndTime",0).toLongLong());
        sendData5.append( quint32toQuint16List(iValue2));

        //6.发送模式2循环次数
        quint16 iValue3 =  static_cast<quint16>(m_MainSettings->value("Repetitions",0).toUInt()) ;
        sendData6.append( iValue3);

        m_MainSettings->endGroup();

        /********************当前数据*************************/
        m_MainSettings->beginGroup(QString("Power%1_Other").arg(i+1));
        //当前段数
        bool CurrentParagraphEnable =  m_MainSettings->value("CurrentParagraphEnable",true).toBool();
        quint16 CurrentParagraph = m_MainSettings->value("CurrentParagraph",true).toUInt();
        if(CurrentParagraphEnable)
        {
            sendData13 << 20;
        }
        else
        {
            sendData13 << CurrentParagraph-1;
        }
        //当前模式
        quint16 CurrentMode =  m_MainSettings->value("CurrentMode",true).toUInt();
        sendData14.append(CurrentMode);
        //设置电流超值
        float CurrentRange = m_MainSettings->value("EleCurrentRange",true).toFloat();
        sendData15.append(floatToQuint16(CurrentRange));

        float VolRange = m_MainSettings->value("EleVolRange",true).toFloat();
        sendData16.append(floatToQuint16(VolRange));

        m_MainSettings->endGroup();

    }

    /*********************模式3*************************/
    sendData7  = sendData1;//模式3的电流等于模式1的电流
    sendData8  = sendData2;//模式3的时间等于模式1的时间
    sendData9  = sendData4;//模式3的开通时间等于模式2的开通时间
    sendData10 = sendData5;//模式3的关闭时间等于模式2的关闭时间
    sendData11 = sendData6;//模式3的循环次数等于模式2的循环次数
    sendData12 = sendData3;//模式3的起始电流等于模式2的起始电流

    /*********************模式3*************************/

    /***1 2 ***在前面的循环中发送了********/

    //3.发送模式2起始电流
    WriteData* writeData3 = new WriteData(1400,sendData3.size(),sendData3);
    emit sig_AddWriteQueue(writeData3);
    //4.发送模式2开通时间
    WriteData* writeData4 = new WriteData(2890,sendData4.size(),sendData4);
    emit sig_AddWriteQueue(writeData4);
    //5.发送模式2关闭时间
    WriteData* writeData5 = new WriteData(2930,sendData5.size(),sendData5);
    emit sig_AddWriteQueue(writeData5);
    //6.发送模式2循环次数
    WriteData* writeData6 = new WriteData(75,sendData6.size(),sendData6);
    emit sig_AddWriteQueue(writeData6);
    /*在前面循环中发
    //7.发送模式3电流
    WriteData* writeData7 = new WriteData(2150,sendData7.size(),sendData7);
    emit sig_AddWriteQueue(writeData7);
    //8.发送模式3时间
    WriteData* writeData8 = new WriteData(1500,sendData8.size(),sendData8);
    emit sig_AddWriteQueue(writeData8);
    */
    //9.发送模式3开通时间
    WriteData* writeData9 = new WriteData(2962,sendData9.size(),sendData9);
    emit sig_AddWriteQueue(writeData9);
    //10.发送模式3关闭时间
    WriteData* writeData10 = new WriteData(2994,sendData10.size(),sendData10);
    emit sig_AddWriteQueue(writeData10);
    //11.发送模式3循环次数
    WriteData* writeData11 = new WriteData(3026,sendData11.size(),sendData11);
    emit sig_AddWriteQueue(writeData11);
    //12.发送模式3开通电压 即起始电流
    WriteData* writeData12 = new WriteData(3050,sendData12.size(),sendData12);
    emit sig_AddWriteQueue(writeData12);
    //13.当前段数发送
    WriteData* writeData13 = new WriteData(58,sendData13.size(),sendData13);
    emit sig_AddWriteQueue(writeData13);
    //14.当前模式发送
    WriteData* writeData14 = new WriteData(3300,sendData14.size(),sendData14);
    emit sig_AddWriteQueue(writeData14);
    //15.电流超值发送
    WriteData* writeData15 = new WriteData(3170,sendData15.size(),sendData15);
    emit sig_AddWriteQueue(writeData15);

    //16.电压超值发送
    WriteData* writeData16 = new WriteData(3202,sendData16.size(),sendData16);
    emit sig_AddWriteQueue(writeData16);
    //emit sig_HandleWriteQueue();//执行写操作


}

//样式
void MainWindow::loadStyle(QString currentStyle)
{
    QString styleFileName;
    if(currentStyle == "black")
    {
        foreach (auto FunctionForm, m_FunctionForms) {
            FunctionForm->setGroupBoxTitleText(true);
        }
        styleFileName = ":/res/qss/style.css";
    }
    else if(currentStyle == "gray")
    {
        styleFileName = ":/res/qss/grayStyle.css";
    }
    else if(currentStyle == "white")
    {
        foreach (auto FunctionForm, m_FunctionForms) {
            FunctionForm->setGroupBoxTitleText(true);
        }
        styleFileName = ":/res/qss/whiteStyle.css";
    }
    else if(currentStyle == "Multiple")
    {
        foreach (auto FunctionForm, m_FunctionForms) {
            FunctionForm->setGroupBoxTitleText(false);
        }
        styleFileName = ":/res/qss/MultipleColors.css";
    }
    else if(currentStyle == "original")
    {
        qApp->setStyleSheet("");
        return;
    }
    else
    {
        return;
    }
    QString style;
    if (!QFileInfo::exists(styleFileName))
    {
        return;
    }
    QFile fh(styleFileName);
    if (fh.open(QFile::ReadOnly | QFile::Text))
    {
        style = fh.readAll();
        fh.close();
    }
    else
    {
        qWarning()<<"open file"<<styleFileName<<"error!";
    }
    qApp->setStyleSheet(style);
}
/*
void MainWindow::InitSendIniData()
{
    //发送模式一的段落数
    QList<quint16> sendData;
    for(int i = 1; i <= 16;i++)
    {
        m_MainSettings->beginGroup(QString("Power%1_Other").arg(i));
        quint16 CurrentParagraph = m_MainSettings->value("CurrentParagraph",20).toUInt();           //当前的段， int
        bool CurrentParagraphEnable = m_MainSettings->value("CurrentParagraphEnable",true).toBool();//当前的段使能  bool
        if(CurrentParagraphEnable)
        {
            sendData << 20;
        }
        else
        {
            sendData << static_cast<quint16>(CurrentParagraph-1);
        }
        m_MainSettings->endGroup();
    }


    emit sig_SetWriteStartAddressAndRegisterCount(58,16,sendData);
//        emit sig_SetWriteStartAddressAndRegisterCount(75,16,sendData);
    QTimer::singleShot(300,[=]()
    {
        emit sig_SetWriteStartAddressAndRegisterCount(58,16,sendData);
//        emit sig_SetWriteStartAddressAndRegisterCount(75,16,sendData);
    });

}
*/

void MainWindow::increaseFontSize(QWidget *widget,int increment)
{
    if (!widget)
        return;

    // 获取当前字体并修改大小
    QFont font = widget->font();
    font.setPointSize(font.pointSize() + increment);
    widget->setFont(font);

    // 递归遍历所有子控件
    for (QObject *child : widget->children())
    {
        if (QWidget *childWidget = qobject_cast<QWidget *>(child))
        {
            increaseFontSize(childWidget, increment);
        }
    }
}

